package com.service.impl;

import com.DTO.ChatRecordDTO;
import com.DTO.PageParam;
import com.Factory.CharRecordFactory;
import com.Result.ChatRecordResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.entity.ChatRecord;
import com.mapper.ChatRecordMapper;
import com.service.ChatRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author XTC
 * @since 2024-07-10
 */
@Service
public class ChatRecordServiceImpl extends ServiceImpl<ChatRecordMapper, ChatRecord> implements ChatRecordService {
    @Autowired
    private ChatRecordMapper chatRecordMapper;

    @Autowired
    private CharRecordFactory charRecordFactory;

    @Override
    public boolean saveRecord(ChatRecord record) {
        return this.chatRecordMapper.insert(record) > 0;
    }

    @Override
    public List<ChatRecordResult> getRecordListWithUser(ChatRecordDTO chatRecordDTO) {

        QueryWrapper<ChatRecord> w1 = new QueryWrapper<>();
        w1.eq("target_type", "user")
                .eq("send_user_id", chatRecordDTO.getUserId1())
                .eq("receive_user_id", chatRecordDTO.getUserId2())
                .or(w -> w.eq("receive_user_id", chatRecordDTO.getUserId1())
                        .eq("send_user_id", chatRecordDTO.getUserId2()))
                .orderByDesc("send_time");

        PageParam pageParam = chatRecordDTO.getPageParam();
        Page<ChatRecord> page = new Page<>(pageParam.getCurrent(), pageParam.getSize());

        IPage<ChatRecord> chatRecordIPage = this.chatRecordMapper.selectPage(page, w1);

        List<ChatRecord> chatRecordList = chatRecordIPage.getRecords();
        List<ChatRecordResult> chatRecordResultList = this.charRecordFactory.getChatRecordResult(chatRecordList);
        return chatRecordResultList;
    }

    @Override
    public List<ChatRecordResult> getRecordListWithGroup(ChatRecordDTO chatRecordDTO) {
        QueryWrapper<ChatRecord> w1 = new QueryWrapper<>();
        w1.eq("target_type", "group")
                .eq("receive_user_id", chatRecordDTO.getUserId2())
                .orderByDesc("send_time");
        PageParam pageParam = chatRecordDTO.getPageParam();
        Page<ChatRecord> page = new Page<>(pageParam.getCurrent(), pageParam.getSize());
        IPage<ChatRecord> chatRecordIPage = this.chatRecordMapper.selectPage(page, w1);
        List<ChatRecord> chatRecordList = chatRecordIPage.getRecords();
        return this.charRecordFactory.getChatRecordResult(chatRecordList);
    }
}
